package util;

import org.apache.struts2.ServletActionContext;

import java.io.*;

/**
    将图片存入指定的文件中
 */
public class FileInputOut {

    public static String fileInputOut(String userImg,File imgFile,String uploadDir) throws IOException {
        String dir=ServletActionContext.getServletContext().getRealPath(uploadDir);

        File imgDir = new File(dir);

        if (!imgDir.exists()) {
            imgDir.mkdirs();
        }
        FileInputStream input = null;
        FileOutputStream out = null;

        StringBuffer imgFileName= new StringBuffer(GenerateFileName.generateFileName())
                .append(userImg.substring(userImg.lastIndexOf(".")));

        StringBuffer imgFileDir= new StringBuffer(imgDir.toString())
                .append(File.separator).append(imgFileName);

        StringBuffer imgName= new StringBuffer(uploadDir)
                .append(File.separator).append(imgFileName);
        try {
            out = new FileOutputStream(imgFileDir.toString());
            input = new FileInputStream(imgFile);

            byte[] b = new byte[1024];//每次写入的大小
            int i = 0;
            while ((i = input.read(b)) > 0) {
                out.write(b, 0, i);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
            if (input != null) {
                input.close();
            }
        }
        return imgName.toString();

    }



}
